{% extends "public/base.html" %}
{% load nm %}
{% load js %}

{% block head_resources %}
  {{block.super}}
  {% jsinclude "tables" %}
{% endblock %}

{% block head %}
{{block.super}}
<style type="text/css">
.errorlist { color: red; }
</style>
<script type="text/javascript">
{% nm_js_support %}

$(function() {
    var is_admin = {{visitor.is_admin|yesno:"true,false"}};
    var form = $("#search_form");
    var fsubmit = $("#search_form_submit");
    var perstable = $("#perstable");
    var startmessage = $("#startmessage");
    var emptymessage = $("#emptymessage");
    var tbody = $("tbody", perstable);
    var results = [];
    var ayt_timeout = null;
    var old_query = null;

    function do_search()
    {
        // Collect form fields for submission
        var query = form.serialize();

        // If the query has not changed, do nothing
        if (query == old_query) return;

        fsubmit.hide();
        perstable.hide();
        emptymessage.hide();
        startmessage.hide();

        // Check if the form has been filled
        var has_data = false;
        var data = {};
        var re_fields = { "cn": true, "mn": true, "sn": true, "email": true, "uid": true }
        $.each(form.serializeArray(), function(idx, val) {
            if (val.name == "csrfmiddlewaretoken") return;
            if (val.value == "") return;
            has_data = true;
            console.log("NAME", val.name, re_fields[val.name])
            if (re_fields[val.name])
              data[val.name] = "/" + val.value.replace(/([.*+?^=!:${}()|\[\]\/\\])/g, "\\$1") + "/";
            else
              data[val.name] = val.value;
        });

        // If not, just leave stuff hidden and do nothing
        if (!has_data)
        {
            startmessage.show();
            return;
        }

        $.getJSON("{% url 'api_people' %}", data, function(data, textStatus, jqXHR) {
            tbody.empty();
            $.each(data.r, function(idx, val) {
                var st = ALL_STATUS[val.status];
                var status_changed = new Date(val.status_changed * 1000);
                var tr = $("<tr>");
                // <td val="{|p.status|seq_status}}"><a href="{| url people status=p.status %}">{|p.status|desc_status}}</a></td>
                tr.append($("<td>").attr("val", st.seq).text(st.ldesc));
                // TODO <td>{|p.status_changed|date:"Y-m-d"}}</td>
                tr.append($("<td>").text(status_changed.toISOString().substr(0, 10)));
                // <td><a href="{| p.get_absolute_url }}">{|p.uid|default:"None chosen yet"}}</a></td>
                var uid = val.uid ? val.uid : "None chosen yet";
                tr.append($("<td>").append($("<a>").attr("href", val.url).text(uid)));
                // <td><a href="{| p.get_absolute_url }}">{|p.fullname}}</a></td>
                tr.append($("<td>").append($("<a>").attr("href", val.url).text(val.fullname)));
                tbody.append(tr);
            });

            if (data.r.length > 0)
            {
                perstable.show();
            }
            else
            {
                fsubmit.show();
                emptymessage.show();
            }

            old_query = query;
        });
    }

    function form_changed(ev)
    {
        if (ayt_timeout != null)
            clearTimeout(ayt_timeout);
        ayt_timeout = setTimeout(do_search, 200);
    }

    // Standard tablesorter activation
    perstable.tablesorter({
        textExtraction: function(node) {
            val = node.getAttribute("val");
            if (val == null)
                val = node.textContent || node.innerText;
            return val;
        },
    });

    // Hide submit button when everything is empty
    fsubmit.hide();

    // Hide the persons table if it is empty
    perstable.hide();

    emptymessage.hide();

    // Only submit the form if it is allowed and if there are no results
    form.submit(function(ev) {
        if (!is_admin || results.length > 0)
            ev.preventDefault();
    });

    // form.keypress(form_changed);
    form.keyup(form_changed);
    form.change(form_changed);

/*
{% if not status %}
    var tbody = perstable.find("tbody");
    var cached_rows = {
        "all": tbody.find("tr"),
        "new": tbody.find("tr.new"),
        "dm": tbody.find("tr.dm"),
        "dd": tbody.find("tr.dd"),
        "emeritus": tbody.find("tr.emeritus"),
        "removed": tbody.find("tr.removed"),
    };
    $("a.filter").click(function(el) {
        // Retrieve the filter name
        var filter = this.getAttribute("href").substr(1);

        if (filter == "all")
            cached_rows["all"].show();
        else
        {
            cached_rows["all"].hide();
            cached_rows[filter].show();
        }
        return false;
    });
{% endif %}
*/
});
</script>
{% endblock %}

{% block breadcrumbs %}{{block.super}} / <a href="{% url 'people' %}">people</a>{% endblock %}

{% block relatedpages %}
<a href="{% url 'people' %}">all people</a>
{{block.super}}
{% endblock %}


{% block content %}

<h1>Debian New Member - Find{% if visitor.is_admin %}/create{% endif %} person</h2>

<div id="intro">
Fill in fields of the form to look for people.
{% if visitor.is_admin %}
If the person you are looking for is not found, you can use the same form to
create a new Person record.
{% endif %}
</div>

<form id="search_form" action="{% url 'public_findperson' %}" method="post">{% csrf_token %}
{% for hidden in form.hidden_fields %} {{hidden}} {% endfor %}
{{ form.non_field_errors }}
<table class="personinfo">
    {% for field in form.visible_fields %}
    <tr>
        <th>{{field.label_tag}}</th>
        <td>{{field}} {{field.errors}}</td>
    </tr>
    {% endfor %}
</table>
{% if visitor.is_admin %}
    <input id="search_form_submit" type="submit" value="Create person" />
{% endif %}
</form>

<p id="startmessage">Results are shown as you type.</p>
<p id="emptymessage">No results.</p>

<table id="perstable" class="tablesorter {{class}}">
<thead>
    <tr>
        <th>Status</th>
        <th>Since</th>
        <th>Account name</th>
        <th>Name</th>
    </tr>
</thead>
<tbody>
    {% comment %}
    {% for p in people %}
    <tr class="{{p.simple_status}}">
        {% if not status %}
        <td val="{{p.status|seq_status}}"><a href="{% url 'people' status=p.status %}">{{p.status|desc_status}}</a></td>
        {% endif %}
        <td>{{p.status_changed|date:"Y-m-d"}}</td>
        <td><a href="{{ p.get_absolute_url }}">{{p.uid|default:"None chosen yet"}}</a></td>
        <td><a href="{{ p.get_absolute_url }}">{{p.fullname}}</a></td>
    </tr>
    {% endfor %}
    {% endcomment %}
</tbody>
</table>

{% endblock %}

